import React from 'react';
import { Card, Form, Input, Button, message, Progress } from 'antd';
import { LockOutlined, SafetyOutlined, EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons';
import { useMutation } from '@tanstack/react-query';
import { authApi } from '@/api/auth';

const { Password } = Input;

const ChangePasswordPage: React.FC = () => {
  const [form] = Form.useForm();

  // 修改密码
  const changePasswordMutation = useMutation({
    mutationFn: authApi.changePassword,
    onSuccess: () => {
      message.success('密码修改成功！');
      form.resetFields();
    },
    onError: () => {
      message.error('密码修改失败，请重试');
    },
  });

  // 计算密码强度
  const calculatePasswordStrength = (password: string) => {
    let strength = 0;

    if (password.length >= 8) strength += 25;
    if (password.length >= 12) strength += 25;
    if (/[a-z]/.test(password)) strength += 12.5;
    if (/[A-Z]/.test(password)) strength += 12.5;
    if (/\d/.test(password)) strength += 12.5;
    if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) strength += 12.5;

    return Math.min(strength, 100);
  };

  const getPasswordStrengthColor = (strength: number) => {
    if (strength < 30) return '#ff4d4f';
    if (strength < 60) return '#faad14';
    if (strength < 80) return '#1890ff';
    return '#52c41a';
  };

  const getPasswordStrengthText = (strength: number) => {
    if (strength < 30) return '弱';
    if (strength < 60) return '中';
    if (strength < 80) return '强';
    return '非常强';
  };

  // 验证密码强度
  const validatePasswordStrength = (_: any, value: string) => {
    if (!value) {
      return Promise.reject('请输入新密码');
    }

    if (value.length < 8) {
      return Promise.reject('密码长度至少8位');
    }

    if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(value)) {
      return Promise.reject('密码必须包含大小写字母和数字');
    }

    if (!/[!@#$%^&*(),.?":{}|<>]/.test(value)) {
      return Promise.reject('密码必须包含特殊字符');
    }

    return Promise.resolve();
  };

  // 表单提交
  const handleSubmit = async (values: { oldPassword: string; newPassword: string }) => {
    try {
      await changePasswordMutation.mutateAsync({
        oldPassword: values.oldPassword,
        newPassword: values.newPassword,
      });
    } catch (error) {
      // 密码修改失败
    }
  };

  // 监听新密码变化
  const newPassword = Form.useWatch('newPassword', form);
  const passwordStrength = newPassword ? calculatePasswordStrength(newPassword) : 0;

  return (
    <div style={{ height: '100%', width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'auto' }}>
      <Card title="修改密码" style={{ width: '100%', maxWidth: 600, height: 'auto' }}>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          autoComplete="off"
        >
          <Form.Item
            label="当前密码"
            name="oldPassword"
            rules={[{ required: true, message: '请输入当前密码' }]}
          >
            <Password
              placeholder="请输入当前密码"
              iconRender={(visible) => (visible ? <EyeOutlined /> : <EyeInvisibleOutlined />)}
            />
          </Form.Item>

          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[
              { required: true, message: '请输入新密码' },
              { validator: validatePasswordStrength }
            ]}
          >
            <Password
              placeholder="请输入新密码"
              iconRender={(visible) => (visible ? <EyeOutlined /> : <EyeInvisibleOutlined />)}
            />
          </Form.Item>

          {newPassword && (
            <div style={{ marginBottom: 24 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                <span style={{ fontSize: 14, color: '#666' }}>密码强度：</span>
                <span style={{ color: getPasswordStrengthColor(passwordStrength), fontWeight: 500 }}>
                  {getPasswordStrengthText(passwordStrength)}
                </span>
              </div>
              <Progress
                percent={passwordStrength}
                strokeColor={getPasswordStrengthColor(passwordStrength)}
                showInfo={false}
                size="small"
              />
              <div style={{ fontSize: 12, color: '#999', marginTop: 4 }}>
                密码要求：至少8位，包含大小写字母、数字和特殊字符
              </div>
            </div>
          )}

          <Form.Item
            label="确认新密码"
            name="confirmPassword"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Password
              placeholder="请确认新密码"
              iconRender={(visible) => (visible ? <EyeOutlined /> : <EyeInvisibleOutlined />)}
            />
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={changePasswordMutation.isPending}
              style={{ marginRight: 8 }}
              icon={<LockOutlined />}
            >
              修改密码
            </Button>
            <Button onClick={() => form.resetFields()}>
              重置
            </Button>
          </Form.Item>
        </Form>

        <Card size="small" style={{ marginTop: 24 }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
            <SafetyOutlined style={{ fontSize: 24, color: '#1890ff' }} />
            <div>
              <h4 style={{ margin: '0 0 8px 0' }}>密码安全建议</h4>
              <ul style={{ margin: 0, paddingLeft: 16, color: '#666' }}>
                <li>使用至少8位的复杂密码</li>
                <li>包含大小写字母、数字和特殊字符</li>
                <li>不要使用个人信息或常见词汇</li>
                <li>定期更换密码，不要重复使用</li>
                <li>不要在多个平台使用相同密码</li>
              </ul>
            </div>
          </div>
        </Card>
      </Card>
    </div>
  );
};

export default ChangePasswordPage;